package cn.fss.elasticsearch;

import java.util.Arrays;

import org.elasticsearch.action.DocWriteResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson2.JSON;

import cn.fss.common.core.page.TableDataInfo;
import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
public class ElasticSearchClient {
    
    @Autowired
//    @Qualifier("myESClient")
    private RestHighLevelClient restHighLevelClient;
    
	/**
     * 获得关键词搜索结果
     * @param index
     * @param sourceBuilder
     * @return
     */
    public TableDataInfo selectDocumentList(String index, SearchSourceBuilder sourceBuilder) {
        try {
            SearchRequest request = new SearchRequest(index);
            if (sourceBuilder != null) {
                // 返回实际命中数
                sourceBuilder.trackTotalHits(true);
                request.source(sourceBuilder);
            }
            SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
            if (response.getHits() != null) {
            	System.out.println("total========="+response.getHits().getTotalHits().value);
            	TableDataInfo data = new TableDataInfo();
            	data.setRows(Arrays.asList(response.getHits().getHits()));
            	data.setTotal(response.getHits().getTotalHits().value);
                return data;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    
	/**
     * 插入/修改文档信息
     * @param index 索引
     * @param data  数据
     * @param docId
     */
    public Boolean insertDocument(String index, String docId, Object data) {
        try {
            IndexRequest request = new IndexRequest(index);
            request.timeout(TimeValue.timeValueSeconds(10));//10秒
            request.id(docId);//如果先前已经上传过文件，此时再次插入会更新。
            // 重要！！必须设置管道
            request.setPipeline("attachment");
            request.source(JSON.toJSONString(data), XContentType.JSON);
            IndexResponse response = restHighLevelClient.index(request, RequestOptions.DEFAULT);
            log.info("[es] 插入文档的响应状态: status:{},id:{}", response.status().getStatus(), response.getId());
            String status = response.status().toString();
            if ("CREATED".equals(status) || "OK".equals(status)) {
                log.debug("[es] 插入文档成功! ");
                return true;
            }
        } catch (Exception e) {
            log.error("[es] 插入文档失败",e);
        }
        return false;
    }
    
    /**
     * 删除某个index的docId
     * @param index
     * @param docId
     * @return
     */
    public boolean deleteDocument(String index,String docId) {
    	try {
    		DeleteRequest request = new DeleteRequest(index,docId);
    		DeleteResponse res = restHighLevelClient.delete(request, RequestOptions.DEFAULT);
    		log.info("index:[{}],docId:[{}],进行删除操作，es返回的结果是："+res.getResult());
    		if(res.getResult() == DocWriteResponse.Result.DELETED) {
    			return true;
    		}
    		
    	}catch(Exception ex) {
    		log.error(ex.getMessage(),ex);
    	}
    	return false;
    }
}
